package com.tywj.panda.customer.common.tool

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.DeviceUtils
import com.tywj.panda.customer.common.R
import com.tywj.panda.customer.common.api.CommonApi
import com.tywj.panda.customer.common.cache.CommonCache
import com.tywj.panda.customer.common.entity.UpdateTokenEntity
import com.tywj.panda.customer.common.http.PDObjectCallback
import com.tywj.lib.core.common.util.LogUtil

/**
 * @desc 认证工具类
 * @author June Yang
 * @date 2020/6/20
 */
object AuthorityTool {

    // 设备唯一识别码（退出登录或刷新token失败会重置）
    var uuid = ""
        private set

    var uid = ""
        private set

    // 用户识别码
    var token = ""
        private set

    // 是否正在更新token
    private var isUpdatingToken = false

    // 等待更新token成功的代码块列表
    private val waitUpdateTokenSuccessBlockList = ArrayList<() -> Unit>()

    init {
        token = CommonCache.token
        uuid = CommonCache.uuid
        uid = CommonCache.uid
        if (uuid.isEmpty()) {
            createUUID()
        }
    }

    fun updateToken(token: String) {
        this.token = token
        CommonCache.token = token
    }

    fun clear() {
        token = ""
        CommonCache.token = ""
        createUUID()
    }

    @Synchronized
    fun requestUpdateToken(lifecycleOwner: LifecycleOwner?, successBlock: () -> Unit) {
        waitUpdateTokenSuccessBlockList.add(successBlock)
        LogUtil.d("waitRequestCallbackList size is ${waitUpdateTokenSuccessBlockList.size}.")

        lifecycleOwner?.lifecycle?.let {
            if (it.currentState != Lifecycle.State.DESTROYED) {
                it.addObserver(object : DefaultLifecycleObserver {
                    override fun onDestroy(owner: LifecycleOwner) {
                        super.onDestroy(owner)

                        waitUpdateTokenSuccessBlockList.remove(successBlock)
                    }
                })
            }
        }

        if (isUpdatingToken) {
            return
        }
        isUpdatingToken = true

        CommonApi.updateToken()
            .execute(object :
                PDObjectCallback<UpdateTokenEntity>(UpdateTokenEntity::class.java, true) {
                override fun success(data: UpdateTokenEntity) {
                    LogUtil.d("刷新token成功：" + data.token)
                    updateToken(data.token)

                    waitUpdateTokenSuccessBlockList.forEach {
                        it.invoke()
                    }
                    waitUpdateTokenSuccessBlockList.clear()
                    isUpdatingToken = false
                }

                override fun error(code: Int, message: String) {
                    super.error(code, message)

                    LogUtil.d("刷新token失败")
                    LogoutTool.logout(R.string.common_account_abnormal)

                    waitUpdateTokenSuccessBlockList.clear()
                    isUpdatingToken = false
                }
            })
    }

    private fun createUUID() {
        val uuid = DeviceUtils.getModel() + "-" + java.util.UUID.randomUUID().toString()
        this.uuid = uuid
        CommonCache.uuid = uuid
    }
}